package com.hooper.iot.face.schedule;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hooper.iot.face.components.ChannelRepository;
import com.hooper.iot.face.components.DeviceInfoRespository;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author :     WANGCHENG
 * @Date :     2022/6/7 16:10
 * @Version:
 * @Description
 */
@Component
@Slf4j
public class DeviceStatusJob {
    @Autowired
    private KafkaTemplate kafkaTemplate;
    //存储两种，Gbid-deviceInfo ipv4- deviceInfo
    @Autowired
    DeviceInfoRespository deviceInfoRespository;
    @Autowired
    private ChannelRepository repository;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${device.host}")
    private String baseUrl;
    @Value("${commons.oauth2.client.username}")
    private String userName;
    @Value("${commons.oauth2.client.password}")
    private String password;

    @PostConstruct
    @Scheduled(cron = "*/55 * * * * ?")
    private void changeStatus() {
        getDevice();
        Map<String, JSONObject> map = deviceInfoRespository.getMap();
        map.forEach((key, value) -> {
            if (key.contains(".")) {
                Channel channel = repository.get(key);
                if (channel == null) {
                    sendMessage(value, "offline");
                } else {
                    sendMessage(value, "onfline");
                }
            }
        });
    }


    public void getDevice() {
        Map<String, JSONObject> urlList = new LinkedHashMap<>();
        try {
            String deviceListUrl = baseUrl + "/cdevice-manage/device/ext?includes=id,status,name,ipv4,port,gbid,relatedGbid&f_eq_deviceType=FaceTerminal";
            String s = restTemplate.getForEntity(deviceListUrl, String.class).getBody();
            JSONObject body = JSONObject.parseObject(s);
            JSONArray devices = body.getJSONObject("result").getJSONArray("data");
            if (!devices.isEmpty()) {
                for (Object one : devices) {
                    Map<String, ?> device = (Map) one;
                    String url = baseUrl + "/device-access/devices/" + device.get("id");
                    //第一步获取token值
                    Map<String, String> params = new HashMap();
                    params.put("username", userName);
                    params.put("password", password);
                    HttpEntity<MultiValueMap> requestEntity = new HttpEntity(params, new HttpHeaders());
                    Map result = restTemplate.exchange(baseUrl + "/device-access/oauth2/password", HttpMethod.POST, requestEntity, Map.class).getBody();
                    JSONObject tokenJson = new JSONObject(result);
                    String token;
                    if (tokenJson.get("status").equals(HttpStatus.HTTP_OK)) {
                        token = tokenJson.getJSONObject("result").getString("jwt_token");
                    } else {
                        throw new Exception("获取token失败！");
                    }
                    //第二步获取数据
                    HttpHeaders headers = new HttpHeaders();
                    headers.add("jwt-token", token);
                    HttpEntity httpEntity = new HttpEntity(headers);
                    JSONObject deviceInfo = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JSONObject.class).getBody();
                    if (!StringUtils.isEmpty(device.get("ipv4"))) {
                        deviceInfoRespository.put(JSONObject.parseObject(JSONObject.toJSONString(device)).getString("ipv4"), JSONObject.parseObject(JSONObject.toJSONString(device)));
                        deviceInfoRespository.put(JSONObject.parseObject(JSONObject.toJSONString(device)).getString("relatedGbid"), JSONObject.parseObject(JSONObject.toJSONString(device)));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询一机一档数据失败！" + e.getMessage());
        }
    }


    private void sendMessage(JSONObject object, String status) {
        JSONObject notify = new JSONObject();
        notify.put("devGbId", object.getString("gbid"));
        notify.put("devStatus", status);
        notify.put("timestamp", new Timestamp(System.currentTimeMillis()));
//        log.info("更改设备状态信息为===>" + notify.toJSONString());
        kafkaTemplate.send("DEVICE_STATUS", notify.toJSONString());
    }
}
